package oh.june.keepscreenonwatch;

import java.util.ArrayList;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

public class ApplicationListAdapter extends ArrayAdapter<ApplicationInfo>{
	
	private static int LAYOUT = R.layout.list_applist;
	private LayoutInflater mInflater;
	private Context _context;
	private PackageManager _pm;
	private ArrayList<String> _checkList = new ArrayList<String>();
	
	
	public ApplicationListAdapter(Context context, PackageManager pm) {
		super(context, LAYOUT);
		_context = context;
		_pm = pm;
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}
	
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
//		View v = convertView;
		final ApplicationInfo info = getItem(position);
		if(convertView == null){
			convertView = mInflater.inflate(LAYOUT, null);
		}
		
		ImageView imv = (ImageView)convertView.findViewById(R.id.img_view);
		TextView txt = (TextView)convertView.findViewById(R.id.txt_view);
		txt.setTypeface(Typeface.MONOSPACE);
		final CheckBox chk = (CheckBox)convertView.findViewById(R.id.chk_view);
		chk.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(chk.isChecked()){
					_checkList.add(position+"");
				}else{
					_checkList.remove(position+"");
				}
			}
		});
		
		chk.setChecked(_checkList.contains(position+"") ? true : false);
		imv.setImageDrawable(info.loadIcon(_pm));
		txt.setText(_pm.getApplicationLabel(info).toString().trim());
		return convertView;
	}
	
	
	public ArrayList<ApplicationInfo> getCheckedInfoList(){
		
		ArrayList<ApplicationInfo> infoList = new ArrayList<ApplicationInfo>();
		for(int i=0; i<this.getCount(); i++){
			ApplicationInfo info = this.getItem(i);
			if(_checkList.contains(i + "")){
				infoList.add(info);
			}
		}
		
		return infoList;
	}
	
	class ViewHolder{
		ImageView _imv;
		TextView _txt;
		CheckBox _chk;
	}
	
}
